package com.hd123.rumba.gwt.widget.client.grid;

import java.util.ArrayList;

import com.google.gwt.user.client.rpc.AsyncCallback;

public abstract class PageDataProvider implements DxGridDataProvider {
  protected int pageSize = 15, pageCount, rowCount, totalCount, currentPage = 0;
  protected ArrayList values;
  private boolean needFetch = true;

  public PageDataProvider() {
  }

  public abstract void doFetch(int page, AsyncCallback callback);

  public abstract int getColumnCount();

  public abstract String getData(int row, int col);

  public void fetch(final int page, final AsyncCallback callback) {
//    Window.alert("PageDataProvider.fetch " + System.currentTimeMillis() + " " + page);
    if (needFetch(page)) {
      if (fetchCallback == null)
        fetchCallback = new FetchCallback(callback);
      doFetch(page, fetchCallback);
    } else {
      callback.onSuccess(Boolean.FALSE); // 不需要刷新表格内容
    }
  }
  
  private FetchCallback fetchCallback = null;

  private class FetchCallback implements AsyncCallback {
    AsyncCallback callback;

    public FetchCallback(AsyncCallback callback) {
      this.callback = callback;
    }

    public void onFailure(Throwable caught) {
      callback.onFailure(caught);
    }

    public void onSuccess(Object result) {
//      Window.alert("FetchCallback.onSuccess " + System.currentTimeMillis());
      PageData values = (PageData) result;
      setValues(values);
      setCurrentPage(values.getCurrentPage());
      callback.onSuccess(Boolean.TRUE); // 刷新表格内容
      setNeedFetch(false);
    }
  }

  public boolean needFetch(int page) {
    return needFetch || page != getCurrentPage();
  }

  public void setNeedFetch(boolean needFetch) {
    this.needFetch = needFetch;
  }

  public int getCurrentPage() {
    return currentPage;
  }

  public int getPageCount() {
    return pageCount;
  }

  public int getPageSize() {
    return pageSize;
  }

  public int getRowCount() {
    return rowCount;
  }

  public int getTotalCount() {
    return totalCount;
  }

  public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
  }

  public void setPageCount(int pageCount) {
    this.pageCount = pageCount;
  }

  public void setCurrentPage(int currentPage) {
    this.currentPage = currentPage;
  }

  public void setTotalCount(int totalCount) {
    this.totalCount = totalCount;
  }

  public void setRowCount(int rowCount) {
    this.rowCount = rowCount;
  }

  public void setValues(PageData pageData) {
    setRowCount(pageData.getValues() == null ? 0 : pageData.getValues().size());
    setTotalCount(pageData.getTotalCount());
    setPageCount(pageData.getPageCount());
    values = pageData.getValues();
  }

  public ArrayList getValues() {
    return values;
  }
}
